package main

import (
	"bytes"
	"html/template"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"time"
)

//获取网页模板
func load_Template() *template.Template {
	result := template.New("template")
	template.Must(result.ParseGlob("res/html/*.html"))
	return result
}

// 发送GET请求
func to_Get(url string) string {

	// 超时时间：5秒
	client := &http.Client{Timeout: 5 * time.Second}
	resp, err := client.Get(url)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	var buffer [512]byte
	result := bytes.NewBuffer(nil)
	for {
		n, err := resp.Body.Read(buffer[0:])
		result.Write(buffer[0:n])
		if err != nil && err == io.EOF {
			break
		} else if err != nil {
			panic(err)
		}
	}

	return result.String()
}

//获取天气 key1 采用citycey获取城市天气信息 key2 采用城市中文名获取城市天气信息
func get_Weather(key1 string, key2 string) {
	if key1 != "" {
		mxl_str := []byte(to_Get("http://wthrcdn.etouch.cn/WeatherApi?citykey=" + key1))
		ioutil.WriteFile(`res/xml/data.xml`, mxl_str, 0666)
	}
	if key2 != "" {
		mxl_str := []byte(to_Get("http://wthrcdn.etouch.cn/WeatherApi?city=" + key2))
		ioutil.WriteFile(`res/xml/data.xml`, mxl_str, 0666)
	}

}

func main() {
	//设置监听端口
	server := http.Server{
		Addr: ":8808",
	}
	//加载网页模板
	template := load_Template()
	//设置相应方案
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		//读取form字段
		r.ParseForm()
		citykey := r.FormValue("citykey")
		city := r.FormValue("city")
		file_name := r.URL.Path[1:]
		t := template.Lookup(file_name)
		if t != nil {
			err := t.Execute(w, nil)
			if err != nil {
				log.Fatalln(err.Error())
			}
			if citykey != "" || city != "" {
				get_Weather(citykey, city)
			}

		} else {
			w.WriteHeader(http.StatusNotFound)
		}
	})
	//加载静态资源文件
	http.Handle("/css/", http.FileServer(http.Dir("res")))
	http.Handle("/img/", http.FileServer(http.Dir("res")))
	http.Handle("/js/", http.FileServer(http.Dir("res")))
	http.Handle("/xml/", http.FileServer(http.Dir("res")))
	//启动服务
	server.ListenAndServe()
	//使用宝塔服务器反向代理实现 域名访问
}
